package com.example.bourse.filter;

import com.example.bourse.core.enums.ReqCodeEnum;
import com.example.bourse.core.result.ApiResult;
import com.example.bourse.core.utils.DateUtils;
import com.example.bourse.filter.exception.CustomException;
import com.example.bourse.filter.exception.RootPathException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author wangzhiqi
 * @version 1.0
 * @description: 全局异常过滤器
 * @date 2025/1/15 12:24
 */
@Slf4j
@Component(index = 0)
public class ExceptionFilter implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (CustomException e) {
            ctx.status(e.getCode());
            log.error("业务异常: {}", e.getMessage(), e);
            ctx.render(ApiResult.error(ReqCodeEnum.CUSTOM_EXCEPTION.getCode(), e.getMessage()));
        } catch (RootPathException e) {
            ctx.status(e.getCode());
            log.error("路径异常: {}", e.getMessage());
            ctx.render(ApiResult.error(ReqCodeEnum.PATH_ERROR.getCode(), e.getMessage()));
        } catch (RuntimeException e) {

        } catch (Exception e) {
            ctx.status(500);
            String date = DateUtils.dateToString(new Date(), DateUtils.DATETIME);
            log.error("{} - 服务异常: {}", date, e.getMessage(), e);
            ctx.render(ApiResult.error(ReqCodeEnum.INTERNAL_ERROR.getCode(), date + " - 服务异常"));
        }
    }
}
